<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="formVisible = true" v-if="isAdmin">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="套餐名" value="1"></el-option>
              <el-option label="供应商" value="2"></el-option>
              <el-option label="供应商套餐ID" value="3"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
      </div>
    </div>

    <el-table stripe style="width: 100%"  border fit highlight-current-row ref="tableDataRef" :data="tableData" :key="key" @sort-change="tableSortCge">
      <el-table-column  min-width="50" align="center" prop="id" label="ID"></el-table-column>
      <el-table-column  min-width="50" align="center" prop="name" label="套餐名" sortable="custom">
      </el-table-column>
      <el-table-column  min-width="140" align="center" prop="supplierIdArr" label="供应商套餐ID">
        <template slot-scope="scope">
          <el-select v-show="scope.row.supplierIdArr.length>0" v-model="scope.row.supplierIdArr" placeholder="请选择" multiple disabled>
            <el-option
              v-for="item in scope.row.supplierArr"
              :key="item.id"
              :label="item.nameId"
              :value="item.id.toString()">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column  min-width="180" align="center" prop="supplierIdArr" label="套餐期限">
        <template slot-scope="scope">
          <el-select v-show="scope.row.supplierIdArr.length>0" v-model="scope.row.supplierIdArr" placeholder="请选择" multiple disabled style="width: 220px">
            <el-option
              v-for="item in scope.row.supplierArr"
              :key="item.id"
              :label="item.term"
              :value="item.id.toString()">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column  min-width="50" align="center" prop="create_time" label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time| activateTime}}</template>
      </el-table-column>
      <el-table-column  min-width="50" align="center" prop="admin_name" label="操作账号"></el-table-column>
      <el-table-column v-if="isAdmin" label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="openEdit(scope.row)">编辑</el-button>
            <el-button size="mini" @click="delPlatter(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
                     layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- 添加弹窗 -->
    <el-dialog :title="editSubjects == true ? '编辑套餐' :'添加套餐'" :visible.sync="formVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="40%" @close="addFormclose">
      <el-form :model="addForm"  ref="ruleForm" :rules="rules" class="diolog_adapt" style="width: 600px" >
        <el-form-item label="套餐名称:" label-width="120px" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入套餐名称"></el-input>
        </el-form-item>
        <div v-for="(item,index) in supplierList">
          <el-card>
            <el-form-item label="供应商" label-width="120px" >
              <el-select v-model="item.id" placeholder="请选择供应商" style="flex:1">
                <el-option v-for="s in supplierOptions" :key="s.id" :label="s.name"
                           :value="s.id.toString()"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="套餐ID(供应商)" label-width="120px">
<!--              <el-input  v-model="item.taoCanId" placeholder="请填写套餐id(供应商)" maxlength="12"></el-input>-->
              <el-input maxlength="12" v-model="item.taoCanId" onkeyup="this.value=this.value.replace(/[^\d.]/g,'')" placeholder="请填写套餐id(供应商)"></el-input>

            </el-form-item>
            <el-form-item label="内容年限" label-width="120px">
              <el-input type="number" v-model="item.term" min="0" placeholder="请输入套餐内容年限"></el-input>
            </el-form-item>
            <el-form-item label-width="100px" >
              <el-button icon="el-icon-plus" type="primary" @click="toAddList"></el-button>
              <el-button icon="el-icon-minus" type="danger" @click="toRemoveList(item,index)"></el-button>
            </el-form-item>
          </el-card>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" size="mini" round @click="editPlatter('ruleForm')">确 定
        </el-button>
        <el-button v-else type="primary" @click="addPlatter('ruleForm')" size="mini" round>确定</el-button>
      </div>
    </el-dialog>
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>

</template>

<script scoped>
  import dynamicTable from "@/components/DynamicTable";
  import deleteDialog from "@/components/deleteDialog";
  import tableMini from '@/utils/tableMini.js'
  import {
    addPlatterControl,
    queryPlatterControl, editPlatterControl, delPlatterControl
  } from "@/api/launcherMade";

  export default {
    mixins: [tableMini],
    components: {dynamicTable, deleteDialog},
    data() {
      return {
        key: 1,
        colData: [], //动态控制table
        checkboxVal: ["ID", "图标", "课程名", "课程文件性质", "课程文件大小", "套餐归属", "说明", "适配学龄段"],
        searchTable: "",
        select: "", //搜索条件
        tableData: [],
        listQuery: {
          startSize: 1,
          pageSize: 10,
          userId: localStorage.getItem("ID"),
          is_charge: 1,
        },
        addForm: {
          name: "",
        },
        formVisible: false,
        rules: {
          name: [{required: true, message: '请输入套餐名', trigger: 'blur'},{ min: 0, max: 12, message: '长度需在12个字符内', trigger: 'blur' }],
        },
        editSubjects: false,
        deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
        isAdmin: true,
        supplierList: [{id:"",time:[],taoCanId:'', term:0}],
        supplierOptions: [],
      }
    },
    created() {
      this.getPlatterTableData()
      if (localStorage.getItem("roleName") != '超级管理员' || localStorage.getItem("roleName") == '管理员') {
        this.isAdmin = false
      }
    },
    methods: {
      Refresh() {
        this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), name: undefined}
        this.getPlatterTableData()
      },

      //搜索,1:课程名称
      idnameSearch() {
        if (!this.select) return this.$message.warning("请先选择查询条件");
        this.listQuery.startSize = 1
        this.listQuery.pageSize = 10
        switch (this.select) {
          case '1':
            this.listQuery.name = this.searchTable
            this.getPlatterTableData();
            break;
          case '2':
            this.listQuery.supplier = this.searchTable
            this.getPlatterTableData();
            break;
          case '3':
            this.listQuery.tacCanID = this.searchTable
            this.getPlatterTableData();
            break;
        }
      },
      openEdit(row) {
        this.formVisible = true
        this.editSubjects=true
        this.addForm=row
        this.supplierList = row.originSupplier
      },
      addPlatter(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let addForm = JSON.parse(JSON.stringify(this.addForm))
            addForm.last_ip = sessionStorage.getItem("Ip")
            addForm.userId = localStorage.getItem("ID")
            addForm.supplerList = JSON.stringify(this.supplierList)
            addPlatterControl(addForm).then(res => {
              this.$message.success(res.msg)
              this.getPlatterTableData()
              this.formVisible = false
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },
      getPlatterTableData() {
        queryPlatterControl(this.listQuery).then(res => {
          if(res.code==200){
            this.tableData = res.data
            this.total = res.total
            this.supplierOptions = res.otherData.supplierOptions
          }else{
            this.$message.error(this.res.msg)
          }
        }).catch(err => {
          this.tableData = []
          this.total = 0
        })
      },
      editPlatter(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.$confirm('此操作将永久更改套餐, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let editForm = JSON.parse(JSON.stringify(this.addForm))
              editForm.last_ip = sessionStorage.getItem("Ip")
              editForm.userId = localStorage.getItem("ID")
              editForm.supplerList = JSON.stringify(this.supplierList)
              editPlatterControl(editForm).then(res => {
                this.$message.success(res.msg)
                this.formVisible = false
                this.getPlatterTableData()
              }).catch(err => {
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              });
            });
          } else {
            return false;
          }
        });
      },
      //表格排序事件
      tableSortCge(column) {
        let order = ''
        column.order == "descending" ? order = 'desc' : order = 'asc'
        let sort = [{ field: column.prop, sort: order }]
        this.listQuery.sort = JSON.stringify(sort)
        this.getPlatterTableData()
      },
      delPlatter(id) {
        this.deleteDialogs.show = true
        this.deleteDialogs.deleteId = id
      },
      //删除按钮事件
      deleteEvents() {
        let params = {
          userId: localStorage.getItem("ID"),
          last_ip: sessionStorage.getItem("Ip"),
          id: this.deleteDialogs.deleteId,
        }
        delPlatterControl(params).then(res => {
          if(res.code==200){
            this.$message.success(res.msg)
          }else{
            this.$message.error(res.msg)
          }
          this.getPlatterTableData()
        }).catch(err => {
          console.log("请求失败", err)
        })
      },
      //分页
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getTabularData()
      },
      handleCurrentChange(val) {
        this.listQuery.startSize = val
        this.getTabularData()
      },
      toAddList() {
        this.supplierList.push({
          id:"",
          time:[],
          taoCanId:'',
          term: 0
        })
      },
      toRemoveList(item,index){
        if (this.supplierList.length == 1) {
          this.$message.error('请至少添加一个供应商~')
          return
        }
        let tempList = this.supplierList
        tempList.map((value, i) => {
          if ( i== index) {
            tempList.splice(index, 1);
            this.supplierList = tempList;
          }
        });

      },
      //编辑添加表单关闭事件
      addFormclose() {
        this.editSubjects=false
        this.supplierList = [{id:"",time:[],taoCanId:''}]
        this.$nextTick(() => {
          this.addForm = this.$options.data().addForm
        })
      },
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
